<template>
  <div>
    <!-- 搜索栏 -->
    <el-card id="search">
      <el-row>
        <el-col :span="20">
          <el-input
            v-model="searchModel.username"
            placeholder="用户名查询"
          ></el-input>
          <el-button
            type="primary"
            round
            icon="el-icon-search"
            @click="getRoleList"
            >查询</el-button
          >
        </el-col>
        <el-col :span="4" align="right">
          <el-button
            @click="openEditUI(null)"
            type="primary"
            icon="el-icon-plus"
            circle
          ></el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 结果列表 -->
    <el-card>
      <el-table :data="roleList" stripe style="width: 100%">
        <el-table-column
          prop="id"
          label="ID"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column label="角色" width="200" align="center">
          <template slot-scope="scope">
            <el-tag :type="statusType(scope.row.role)">
              {{ statusText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户状态" width="200" align="center">
          <template slot-scope="scope">
            <el-tag :type="statusType(scope.row.status)" effect="dark">
              {{ statusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div>
              <el-button
                @click="openEditUI(scope.row.id)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
              ></el-button>
              <el-button
                @click="deleteRole(scope.row)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 角色编辑对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @close="clearForm"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="roleForm" ref="roleFormRef" :rules="rules">
        <!-- 角色名称 -->
        <el-form-item
          label="用户名"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input v-model="roleForm.username" autocomplete="off"></el-input>
        </el-form-item>

        <!-- 角色简介 -->
        <el-form-item
          label="密码"
          prop="password"
          :label-width="formLabelWidth"
        >
          <el-input v-model="roleForm.password" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="角色" prop="role" :label-width="formLabelWidth">
          <el-select v-model="roleForm.role" placeholder="请选择角色">
            <el-option
              v-for="(label, value) in roleOptions"
              :key="value"
              :label="label"
              :value="value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="用户状态"
          prop="status"
          :label-width="formLabelWidth"
        >
          <el-switch
            v-model="roleForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import roleApi from "@/api/role"; // 角色管理的 API 路径
export default {
  data() {
    return {
      roleOptions: {
        ADMIN: "管理员",
        ORGANIZER: "组织",
        USER: "用户",
      },
      formLabelWidth: "130px",
      roleForm: {
        id: "",
        username: "",
      },
      dialogFormVisible: false,
      title: "",
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 10,
        type: "",
      },
      roleList: [],
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
        ],
        role: [{ required: true, message: "请选择用户角色", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getRoleList();
  },
  methods: {
    statusType(status) {
      switch (status) {
        case "ORGANIZER":
          return "";
        case "USER":
          return "success";
        case "ADMIN":
          return "info";
        case 1:
          return "success"; // 例如：活跃状态
        case 0:
          return "danger"; // 例如：已冻结状态
        default:
          return "info";
      }
    },
    statusText(status) {
      switch (status) {
        case "ORGANIZER":
          return "组织";
        case "USER":
          return "用户";
        case "ADMIN":
          return "管理员";
        case 1:
          return "活跃";
        case 0:
          return "禁用";
        default:
          return "未知状态";
      }
    },
    deleteRole(role) {
      this.$confirm(`您确认删除角色 ${role.username} 吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          roleApi.deleteRoleById(role.id).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getRoleList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    saveRole() {
      this.$refs.roleFormRef.validate((valid) => {
        if (valid) {
          console.log(this.roleForm);
          roleApi.saveRole(this.roleForm).then(() => {
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.dialogFormVisible = false;
            this.getRoleList();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    clearForm() {
      this.roleForm = { type: "", description: "" };
      this.$refs.roleFormRef.clearValidate();
    },
    cancel() {
      this.dialogFormVisible = false;
      this.clearForm();
    },
    openEditUI(id) {
      if (id == null) {
        this.title = "新增角色";
        this.roleForm = {};
      } else {
        this.title = "修改角色";
        roleApi.getRoleById(id).then((response) => {
          // 获取角色数据时，不填充密码
          const { password, ...roleData } = response.data; // 排除密码字段
          this.roleForm = roleData;
        });
      }
      this.dialogFormVisible = true;
    },
    handleSizeChange(newSize) {
      this.searchModel.pageSize = newSize;
      this.searchModel.pageNo = 1;
      this.getRoleList();
    },
    handleCurrentChange(newPage) {
      this.searchModel.pageNo = newPage;
      this.getRoleList();
    },
    getRoleList() {
      roleApi
        .getRoleList(this.searchModel)
        .then((response) => {
          console.log(response);
          this.total = response.data.total;
          this.roleList = response.data.list;
        })
        .catch((error) => {
          console.error("获取角色信息列表失败", error);
        });
    },
  },
};
</script>
  
  <style>
#search .el-input {
  width: 200px;
  margin-right: 10px;
}
</style>
  